package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.pojo.SqlType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration =configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        Stream.of("select","insert","update","delete")
                .forEach(nodeType->{
                    List<Element> list = rootElement.selectNodes(nodeType);
                    for (Element element : list) {
                        String id = element.attributeValue("id");
                        String resultType = element.attributeValue("resultType");
                        String paramterType = element.attributeValue("paramterType");
                        String sqlText = element.getTextTrim();
                        String nodeName = element.getQName().getName();
                        SqlType sqlType = SqlType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
                        MappedStatement mappedStatement = new MappedStatement();
                        mappedStatement.setId(id);
                        mappedStatement.setResultType(resultType);
                        mappedStatement.setParamterType(paramterType);
                        mappedStatement.setSql(sqlText);
                        mappedStatement.setSqlType(sqlType);
                        String key = namespace+"."+id;
                        configuration.getMappedStatementMap().put(key,mappedStatement);
                    }
                });

    }
}
